import os
import re
import sys
import time
import random
import ctypes
from collections import defaultdict
from enum import Enum
from typing import Dict, List, Tuple, Union, Callable, Any, Optional

# 定义类型枚举
class JanusType(Enum):
    VOID = 'v'
    STRING = 's'
    INTEGER = 'i'
    CHAR = 'c'
    BOOL = 'b'
    POINTER = 'p'
    FUNCTION = 'f'
    FILE_HANDLE = 'o'
    ERROR = 'e'

# Janus值类
class JanusValue:
    def __init__(self, value: Any = None, type: JanusType = JanusType.VOID):
        self.value = value
        self.type = type
    
    def __str__(self) -> str:
        if self.type == JanusType.STRING:
            return self.value
        elif self.type == JanusType.INTEGER:
            return str(self.value)
        elif self.type == JanusType.CHAR:
            return chr(self.value)
        elif self.type == JanusType.BOOL:
            return "true" if self.value else "false"
        elif self.type == JanusType.FILE_HANDLE:
            return f"<file:{self.value}>"
        elif self.type == JanusType.POINTER:
            return f"<ptr:{self.value}>"
        elif self.type == JanusType.FUNCTION:
            return f"<func:{self.value}>"
        return "()"
    
    def __repr__(self) -> str:
        return f"JanusValue({self.value}, {self.type})"
    
    def to_int(self) -> int:
        if self.type == JanusType.STRING:
            try:
                return int(self.value)
            except ValueError:
                return 0
        elif self.type == JanusType.CHAR:
            return ord(self.value) if isinstance(self.value, str) else self.value
        elif self.type == JanusType.BOOL:
            return 1 if self.value else 0
        elif self.type == JanusType.POINTER:
            return id(self.value)
        return self.value if self.type == JanusType.INTEGER else 0
    
    def to_str(self) -> str:
        if self.type == JanusType.INTEGER:
            return str(self.value)
        elif self.type == JanusType.CHAR:
            return chr(self.value)
        elif self.type == JanusType.BOOL:
            return "true" if self.value else "false"
        elif self.type == JanusType.POINTER:
            return f"[ptr]{self.value}"
        return self.value if self.type == JanusType.STRING else ""
    
    def to_bool(self) -> bool:
        if self.type == JanusType.INTEGER:
            return self.value != 0
        elif self.type == JanusType.STRING:
            return bool(self.value)
        elif self.type == JanusType.CHAR:
            return self.value != 0
        elif self.type == JanusType.POINTER:
            return self.value is not None
        return bool(self.value) if self.type == JanusType.BOOL else False

# Janus解释器类
class JanusInterpreter:
    def __init__(self):
        self.ops: List[str] = []
        self.on = 0
        self.ling = 0
        self.JANpost = os.path.basename(sys.argv[0])
        self.vmap: Dict[str, JanusValue] = {}
        self.tokens: Dict[str, Callable[[str], JanusValue]] = {}
        self.return_value = JanusValue()
        self.debug_mode = False
        self.seed = int(time.time())
        self.init_tokens()
    
    def init_tokens(self):
        # 内置函数和操作符定义
        self.tokens = {
            "func": lambda line: JanusValue(),
            "print": self._print,
            "Debug": lambda line: JanusValue(),
            "let": self._let,
            "+": self._add,
            "-": self._sub,
            "*": self._mul,
            "/": self._div,
            "if": self._if,
            "}": lambda line: JanusValue(),
            "while": self._while,
            "true": lambda line: JanusValue(True, JanusType.BOOL),
            "false": lambda line: JanusValue(False, JanusType.BOOL),
            ">": self._gt,
            "<": self._lt,
            ">=": self._ge,
            "<=": self._le,
            "!": self._not,
            "&&": self._and,
            "||": self._or,
            "&": self._bitand,
            "|": self._bitor,
            "^": self._bitxor,
            "%": self._mod,
            "==": self._eq,
            "!=": self._neq,
            "ret": self._ret,
            "]": self._ptr,
            "JANpost": lambda line: JanusValue(self.JANpost, JanusType.STRING),
            "WIN32": lambda line: JanusValue(os.name == 'nt', JanusType.BOOL),
            "shell": self._shell,
            "scan": self._scan,
            "input": lambda line: JanusValue(input(), JanusType.STRING),
            "bcmint": self._bcmint,
            "bcmstr": self._bcmstr,
            "bcmchar": self._bcmchar,
            "bcmbool": self._bcmbool,
            "bcmptr": self._bcmptr,
            "bcmfunc": self._bcmfunc,
            "new": self._new,
            "padd": self._padd,
            "srand": self._srand,
            "rand": self._rand,
            "open": self._open,
            "out": self._out,
            "close": self._close,
            "in": self._in,
            "line": self._line,
            "seek": self._seek,
            "tag": lambda line: JanusValue(),
            "goto": self._goto,
            "()": lambda line: JanusValue(),
            "import": self._import,
            "Import": self._import,
        }
    
    def parse_escape(self, s: str) -> str:
        """处理转义字符"""
        escape_map = {
            'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n',
            'r': '\r', 't': '\t', 'v': '\v', '\\': '\\',
            "'": "'", '"': '"', 'e': '\033', 's': ' '
        }
        result = []
        i = 0
        while i < len(s):
            if s[i] == '\\' and i + 1 < len(s):
                if s[i+1] in escape_map:
                    result.append(escape_map[s[i+1]])
                    i += 2
                    continue
            result.append(s[i])
            i += 1
        return ''.join(result)
    
    def tokenize(self, line: str) -> List[str]:
        """将一行代码分割为tokens"""
        tokens = []
        current = []
        in_string = False
        quote_char = None
        escape = False
        
        for char in line:
            if escape:
                current.append(char)
                escape = False
                continue
                
            if char == '\\':
                escape = True
                current.append(char)
                continue
                
            if in_string:
                current.append(char)
                if char == quote_char:
                    in_string = False
                    quote_char = None
                    tokens.append(''.join(current))
                    current = []
                continue
                
            if char in ('"', "'"):
                in_string = True
                quote_char = char
                current = [char]
                continue
                
            if char.isspace():
                if current:
                    tokens.append(''.join(current))
                    current = []
                continue
                
            if char in ('#', '{'):
                if current:
                    tokens.append(''.join(current))
                tokens.append(char)
                current = []
                continue
                
            current.append(char)
        
        if current:
            tokens.append(''.join(current))
        
        return tokens
    
    def cut(self):
        """预处理代码行"""
        for i in range(self.ling, len(self.ops)):
            line = self.ops[i]
            if not line or line == "Debug":
                continue
            self.ops[i] = ' '.join(self.tokenize(line))
    
    def pexpl(self, line: str) -> JanusValue:
        """解释表达式"""
        tokens = self.tokenize(line)
        if not tokens:
            return JanusValue()
        
        first = tokens[0]
        rest = ' '.join(tokens[1:])
        
        if not first:
            return JanusValue()
        
        if first.startswith('#'):
            return JanusValue()
        
        if first.startswith("'") and first.endswith("'"):
            content = self.parse_escape(first[1:-1])
            return JanusValue(ord(content[0]) if content else 0, JanusType.CHAR)
        
        if first.startswith('"') and first.endswith('"'):
            content = self.parse_escape(first[1:-1])
            return JanusValue(content, JanusType.STRING)
        
        if first.isdigit() or (first[0] == '-' and first[1:].isdigit()):
            return JanusValue(int(first), JanusType.INTEGER)
        
        if first in self.tokens:
            return self.tokens[first](rest)
        
        # 处理指针解引用
        if first.startswith('[') and first.endswith(']'):
            ptr_name = first[1:-1].strip()
            ptr_value = self.vmap.get(ptr_name, JanusValue())
            if ptr_value.type == JanusType.STRING:
                return self.pexpl(ptr_value.value)
            return ptr_value
        
        # 处理变量和函数
        if first in self.vmap:
            var = self.vmap[first]
            if var.type == JanusType.FUNCTION:
                # 函数调用
                saved_ling = self.ling
                self.ling = var.value
                
                # 解析参数
                param_count = int(var.value_str) if var.value_str.isdigit() else 0
                for i in range(1, param_count + 1):
                    arg = self.pexpl(rest)
                    rest = rest[len(rest):]  # 消耗参数
                    self.vmap[f"var{i}"] = arg
                
                result = self.explain()
                self.ling = saved_ling
                return result
            return var
        
        print(f"Undefined token: {first}", file=sys.stderr)
        print(f"That line: {self.ops[self.ling]}", file=sys.stderr)
        return JanusValue(None, JanusType.ERROR)
    
    def explain(self) -> JanusValue:
        """解释执行代码"""
        try:
            while self.ling < len(self.ops):
                line = self.ops[self.ling]
                if not line:
                    self.ling += 1
                    continue
                
                self.pexpl(line)
                self.ling += 1
        except ReturnException:
            self.ling += 1
            return self.return_value
        
        return JanusValue()
    
    def reader(self, filename: str):
        """读取Janus脚本文件"""
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line:
                        continue
                    
                    self.ops.append(line)
                    self.on += 1
                    
                    tokens = self.tokenize(line)
                    if not tokens:
                        continue
                    
                    first = tokens[0]
                    if first == "func":
                        if len(tokens) >= 2:
                            func_name = tokens[1]
                            param_count = tokens[2] if len(tokens) >= 3 else "0"
                            self.vmap[func_name] = JanusValue(self.on, JanusType.FUNCTION)
                            self.vmap[func_name].value_str = param_count
                    elif first == "Import" or first == "import":
                        if len(tokens) >= 2:
                            import_file = tokens[1]
                            if first == "import":
                                import_file = os.path.join(os.path.dirname(sys.argv[0]), "lib", import_file)
                            self.reader(import_file)
                    elif first == "tag":
                        if len(tokens) >= 2:
                            tag_name = tokens[1]
                            self.vmap[tag_name] = JanusValue(self.on, JanusType.FUNCTION)
        except FileNotFoundError:
            print(f"File not found: {filename}", file=sys.stderr)
    
    # ========== 内置函数实现 ==========
    def _print(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        for token in tokens:
            value = self.pexpl(token)
            print(value, end='')
        print()
        return JanusValue()
    
    def _let(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if not tokens:
            return JanusValue(None, JanusType.ERROR)
        
        var_name = tokens[0]
        # 处理指针赋值
        if var_name.startswith('[') and var_name.endswith(']'):
            ptr_name = var_name[1:-1].strip()
            ptr_value = self.vmap.get(ptr_name, JanusValue())
            if ptr_value.type == JanusType.STRING:
                var_name = ptr_value.value
        
        value_expr = ' '.join(tokens[1:])
        value = self.pexpl(value_expr)
        self.vmap[var_name] = value
        return value
    
    def _add(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        if a.type == JanusType.STRING or b.type == JanusType.STRING:
            return JanusValue(a.to_str() + b.to_str(), JanusType.STRING)
        return JanusValue(a.to_int() + b.to_int(), JanusType.INTEGER)
    
    def _sub(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() - b.to_int(), JanusType.INTEGER)
    
    def _mul(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() * b.to_int(), JanusType.INTEGER)
    
    def _div(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        if b.to_int() == 0:
            print("Division by zero", file=sys.stderr)
            return JanusValue(0, JanusType.INTEGER)
        return JanusValue(a.to_int() // b.to_int(), JanusType.INTEGER)
    
    def _if(self, line: str) -> JanusValue:
        cond = self.pexpl(line)
        if not cond.to_bool():
            # 跳过代码块
            depth = 1
            self.ling += 1
            while self.ling < len(self.ops) and depth > 0:
                tokens = self.tokenize(self.ops[self.ling])
                if tokens and tokens[0] == "if":
                    depth += 1
                elif tokens and tokens[0] == "while":
                    depth += 1
                elif tokens and tokens[0] == "}":
                    depth -= 1
                self.ling += 1
            self.ling -= 1  # 调整位置
        return JanusValue()
    
    def _while(self, line: str) -> JanusValue:
        start_line = self.ling
        cond_line = line
        
        while True:
            # 检查条件
            cond = self.pexpl(cond_line)
            if not cond.to_bool():
                break
            
            # 执行代码块
            self.ling = start_line + 1
            depth = 1
            while self.ling < len(self.ops) and depth > 0:
                tokens = self.tokenize(self.ops[self.ling])
                if tokens and tokens[0] == "if":
                    depth += 1
                elif tokens and tokens[0] == "while":
                    depth += 1
                elif tokens and tokens[0] == "}":
                    depth -= 1
                
                # 执行当前行
                if depth > 0:
                    self.pexpl(self.ops[self.ling])
                
                self.ling += 1
        
        # 跳过整个while块
        self.ling = start_line
        depth = 1
        while self.ling < len(self.ops) and depth > 0:
            tokens = self.tokenize(self.ops[self.ling])
            if tokens and tokens[0] == "if":
                depth += 1
            elif tokens and tokens[0] == "while":
                depth += 1
            elif tokens and tokens[0] == "}":
                depth -= 1
            self.ling += 1
        self.ling -= 1  # 调整位置
        
        return JanusValue()
    
    def _gt(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() > b.to_int(), JanusType.BOOL)
    
    def _lt(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() < b.to_int(), JanusType.BOOL)
    
    def _ge(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() >= b.to_int(), JanusType.BOOL)
    
    def _le(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() <= b.to_int(), JanusType.BOOL)
    
    def _not(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        return JanusValue(not a.to_bool(), JanusType.BOOL)
    
    def _and(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_bool() and b.to_bool(), JanusType.BOOL)
    
    def _or(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_bool() or b.to_bool(), JanusType.BOOL)
    
    def _bitand(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() & b.to_int(), JanusType.INTEGER)
    
    def _bitor(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() | b.to_int(), JanusType.INTEGER)
    
    def _bitxor(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        return JanusValue(a.to_int() ^ b.to_int(), JanusType.INTEGER)
    
    def _mod(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        if b.to_int() == 0:
            print("Modulo by zero", file=sys.stderr)
            return JanusValue(0, JanusType.INTEGER)
        return JanusValue(a.to_int() % b.to_int(), JanusType.INTEGER)
    
    def _eq(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        if a.type == b.type:
            if a.type == JanusType.INTEGER:
                return JanusValue(a.value == b.value, JanusType.BOOL)
            return JanusValue(a.to_str() == b.to_str(), JanusType.BOOL)
        return JanusValue(False, JanusType.BOOL)
    
    def _neq(self, line: str) -> JanusValue:
        a = self.pexpl(line)
        b = self.pexpl(line)
        if a.type == b.type:
            if a.type == JanusType.INTEGER:
                return JanusValue(a.value != b.value, JanusType.BOOL)
            return JanusValue(a.to_str() != b.to_str(), JanusType.BOOL)
        return JanusValue(True, JanusType.BOOL)
    
    def _ret(self, line: str) -> JanusValue:
        self.return_value = self.pexpl(line)
        raise ReturnException()
    
    def _ptr(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if tokens:
            ptr_name = tokens[0]
            if ptr_name.startswith('[') and ptr_name.endswith(']'):
                ptr_name = ptr_name[1:-1].strip()
                ptr_value = self.vmap.get(ptr_name, JanusValue())
                if ptr_value.type == JanusType.STRING:
                    ptr_name = ptr_value.value
            return JanusValue(ptr_name, JanusType.POINTER)
        return JanusValue("", JanusType.POINTER)
    
    def _shell(self, line: str) -> JanusValue:
        cmd = self.pexpl(line).to_str()
        return JanusValue(os.system(cmd), JanusType.INTEGER)
    
    def _scan(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        for var_name in tokens:
            if var_name in self.vmap:
                var = self.vmap[var_name]
                input_val = input()
                if var.type == JanusType.STRING:
                    var.value = input_val
                elif var.type == JanusType.INTEGER:
                    try:
                        var.value = int(input_val)
                    except ValueError:
                        var.value = 0
                elif var.type == JanusType.CHAR:
                    var.value = ord(input_val[0]) if input_val else 0
                elif var.type == JanusType.BOOL:
                    var.value = input_val.lower() == "true"
        return JanusValue()
    
    def _bcmint(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        return JanusValue(val.to_int(), JanusType.INTEGER)
    
    def _bcmstr(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        return JanusValue(val.to_str(), JanusType.STRING)
    
    def _bcmchar(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        if val.type == JanusType.STRING and val.value:
            return JanusValue(ord(val.value[0]), JanusType.CHAR)
        return JanusValue(val.to_int(), JanusType.CHAR)
    
    def _bcmbool(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        return JanusValue(val.to_bool(), JanusType.BOOL)
    
    def _bcmptr(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        if val.type == JanusType.STRING:
            return JanusValue(val.value, JanusType.POINTER)
        return JanusValue(str(id(val)), JanusType.POINTER)
    
    def _bcmfunc(self, line: str) -> JanusValue:
        val = self.pexpl(line)
        if val.type == JanusType.STRING and val.value in self.vmap:
            func = self.vmap[val.value]
            if func.type == JanusType.FUNCTION:
                return func
        print(f"Not a function: {val}", file=sys.stderr)
        return JanusValue(None, JanusType.ERROR)
    
    def _new(self, line: str) -> JanusValue:
        type_char = self.pexpl(line).to_int()
        count = self.pexpl(line).to_int()
        
        # 创建对象数组
        base_name = f":{random.randint(1000,9999)}$"
        for i in range(count):
            var_name = f"{base_name}{i}"
            self.vmap[var_name] = JanusValue(type=JanusType(type_char))
        
        return JanusValue(f"{base_name}0", JanusType.POINTER)
    
    def _padd(self, line: str) -> JanusValue:
        ptr = self.pexpl(line)
        offset = self.pexpl(line).to_int()
        
        if ptr.type != JanusType.POINTER:
            print("Invalid pointer", file=sys.stderr)
            return ptr
        
        # 解析指针名称和索引
        match = re.match(r'([^0-9]+)(\d+)$', ptr.value)
        if not match:
            print("Invalid pointer format", file=sys.stderr)
            return ptr
        
        base = match.group(1)
        index = int(match.group(2))
        new_index = index + offset
        return JanusValue(f"{base}{new_index}", JanusType.POINTER)
    
    def _srand(self, line: str) -> JanusValue:
        seed = self.pexpl(line).to_int()
        self.seed = seed
        random.seed(seed)
        return JanusValue()
    
    def _rand(self, line: str) -> JanusValue:
        self.seed = (self.seed * 214013 + 2531011) % 2**32
        return JanusValue((self.seed >> 16) & 0x7FFF, JanusType.INTEGER)
    
    def _open(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if len(tokens) < 2:
            return JanusValue(None, JanusType.ERROR)
        
        filename = self.pexpl(tokens[0]).to_str()
        mode = self.pexpl(tokens[1]).to_str()
        
        try:
            f = open(filename, mode)
            return JanusValue(f, JanusType.FILE_HANDLE)
        except IOError as e:
            print(f"Open failed: {filename} - {str(e)}", file=sys.stderr)
            return JanusValue(None, JanusType.ERROR)
    
    def _out(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if not tokens:
            return JanusValue()
        
        file_val = self.pexpl(tokens[0])
        if file_val.type != JanusType.FILE_HANDLE or not file_val.value:
            print("Invalid file handle", file=sys.stderr)
            return JanusValue()
        
        f = file_val.value
        for token in tokens[1:]:
            val = self.pexpl(token)
            f.write(val.to_str())
        return JanusValue()
    
    def _close(self, line: str) -> JanusValue:
        file_val = self.pexpl(line)
        if file_val.type == JanusType.FILE_HANDLE and file_val.value:
            file_val.value.close()
        return JanusValue()
    
    def _in(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if not tokens:
            return JanusValue()
        
        file_val = self.pexpl(tokens[0])
        if file_val.type != JanusType.FILE_HANDLE or not file_val.value:
            print("Invalid file handle", file=sys.stderr)
            return JanusValue()
        
        f = file_val.value
        for var_name in tokens[1:]:
            if var_name in self.vmap:
                var = self.vmap[var_name]
                if var.type == JanusType.STRING:
                    var.value = f.readline().strip()
                elif var.type == JanusType.INTEGER:
                    try:
                        var.value = int(f.readline().strip())
                    except ValueError:
                        var.value = 0
        return JanusValue()
    
    def _line(self, line: str) -> JanusValue:
        file_val = self.pexpl(line)
        if file_val.type != JanusType.FILE_HANDLE or not file_val.value:
            print("Invalid file handle", file=sys.stderr)
            return JanusValue("", JanusType.STRING)
        
        f = file_val.value
        content = f.readline()
        if content:
            return JanusValue(content.strip(), JanusType.STRING)
        return JanusValue("", JanusType.STRING)
    
    def _seek(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if len(tokens) < 2:
            return JanusValue()
        
        file_val = self.pexpl(tokens[0])
        if file_val.type != JanusType.FILE_HANDLE or not file_val.value:
            print("Invalid file handle", file=sys.stderr)
            return JanusValue()
        
        offset = self.pexpl(tokens[1]).to_int()
        whence = 0  # SEEK_SET
        if len(tokens) > 2:
            whence_str = tokens[2].lower()
            if whence_str == "cur":
                whence = 1
            elif whence_str == "end":
                whence = 2
        
        file_val.value.seek(offset, whence)
        return JanusValue()
    
    def _goto(self, line: str) -> JanusValue:
        target = self.pexpl(line).to_int()
        if 0 <= target < len(self.ops):
            self.ling = target - 1  # 因为ling会在主循环中递增
        return JanusValue()
    
    def _import(self, line: str) -> JanusValue:
        tokens = self.tokenize(line)
        if tokens:
            filename = tokens[0]
            self.reader(filename)
        return JanusValue()

# 自定义异常用于实现return
class ReturnException(Exception):
    pass

def main():
    print("IJanus[版本1.0.0]")
    
    janus = JanusInterpreter()
    if len(sys.argv) > 1:
        janus.reader(sys.argv[1])
        janus.cut()
        start_time = time.time()
        result = janus.explain()
        elapsed = time.time() - start_time
        
        if janus.debug_mode:
            print("\n--------------------------------")
            print(f"Process exited after {elapsed:.3f} seconds with return value {result}")
    else:
        # 交互模式
        print("Entering interactive mode. Type '#end' to execute, '#exit' to quit")
        while True:
            try:
                command = input("> ")
                if command == "#end":
                    janus.cut()
                    start_time = time.time()
                    result = janus.explain()
                    elapsed = time.time() - start_time
                    
                    if janus.debug_mode:
                        print("\n--------------------------------")
                        print(f"Process exited after {elapsed:.3f} seconds with return value {result}")
                    
                    # 重置状态
                    janus.ops = []
                    janus.on = 0
                    janus.ling = 0
                elif command == "#clear":
                    janus.vmap.clear()
                    janus.ops = []
                    janus.on = 0
                    janus.ling = 0
                    print("State cleared")
                elif command == "#show":
                    janus.debug_mode = True
                    print("Debug mode enabled")
                elif command == "#hide":
                    janus.debug_mode = False
                    print("Debug mode disabled")
                elif command == "#exit":
                    break
                else:
                    janus.ops.append(command)
                    janus.on += 1
            except KeyboardInterrupt:
                print("\nInterrupted")
                break
            except Exception as e:
                print(f"Error: {str(e)}")

if __name__ == "__main__":
    main()